-- UIEquipsOperation
-- Create by luohj Jan/15/2015
-- 装备操作界面

UIEquipsOperation = class("UIEquipsOperation",function()
    return cc.Layer:create();
end);

function UIEquipsOperation.create(classId, operateType, isEquiped, extraPara)
    return UIEquipsOperation.new(classId, operateType, isEquiped, extraPara);
end

-- 内部函数
local combineProps;

-- 装备操作类型
EQUIP_OPERATE_UNEQUIP           = 0;   -- 卸下
EQUIP_OPERATE_EQUIP             = 1;   -- 装备
EQUIP_OPERATE_BLACKSMITH        = 2;   -- 工坊操作
EQUIP_OPERATE_SUBMIT            = 3;   -- 提交操作
EQUIP_OPERATE_RISKER            = 4;   -- 冒险系装备根据实际装显示操作

-- 构造函数
function UIEquipsOperation:ctor(classId, operateType, isEquiped, extraPara)
    -- 初始化
    self:setName("UIEquipsOperation");
    local node = cc.CSLoader:createNode("layout/equip/equipOperate.csb");
    self:addChild(node);
    self.node = node;
    local CT = node:getChildByName("CT");
    self.CT = CT;
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录装备id和操作类型
    self.classId = classId;
    operateType = operateType or EQUIP_OPERATE_UNEQUIP;
    self.operateType = operateType;
    self.isEquiped = isEquiped; -- 该装备是否穿在身上

    -- 额外数据
    self.extraPara = extraPara or {};

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 合并属性
local function combineProps(props)
    local arrangeProp = {};
    local tonumber = sys_tonumber;
    local tostring = tostring;
    local dup = table.copy;

    for _, prop in ipairs(props) do
        local key = tostring(prop[2]);
        local propId = tonumber(prop[1]) or 0;

        arrangeProp[propId] = arrangeProp[propId] or {};

        local arr = arrangeProp[propId][key];

        if not arr then
            arr = dup(prop);
        else
            arr[3] = arr[3] + tonumber(prop[3]) or 0;
        end

        if arr[4] == -1 or prop[4] == -1 then
            arr[4] = -1;
        else
            arr[4] = math.max(arr[4], prop[4]);
        end

        arrangeProp[propId][key] = arr;
    end

    local combineProp = {};
    for _, prop in pairs(arrangeProp) do
        for _, v in pairs(prop) do
            table.insert(combineProp, v);
        end
    end

    return combineProp;
end

-- 重绘
function UIEquipsOperation:redraw()
    local itemInfo = ItemM.query(self.classId);
    local equipInfo = EquipM.query(self.classId);

    if not itemInfo then
        error("物品(%s)不存在", self.classId);
        return;
    end

    -- 设置装备阶位
    local rank = EquipM.getRealRank(self.classId);--   equipInfo["rank"];
    self.rank = rank;

    -- 星级控件
    local starNode = self.CT:getChildByName("star_node");

    local starLayer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");

    if starLayer then
        starNode:removeAllChildren();
        starNode:addChild(starLayer);
    end

    -- 设置装备名称
    local nameLabel = self.CT:getChildByName("name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(itemInfo["name"]);

    -- 设置装备描述
    local descLabel = self.CT:getChildByName("description");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    descLabel:setString(ItemM.getItemDesc(self.classId));

    -- 设置装备效果
    local effectLabel = self.CT:getChildByName("effect");
    local props = EquipM.fetchEquipProp(self.classId);
    local equipEffectTxt = EquipM.getEquipPropDesc(props, self.classId, self.isEquiped);

    -- 如果效果描述为空，且配置了detail，则取原始的detail
    if #props == 0 and equipInfo.detail ~= "" then
        equipEffectTxt = equipInfo.detail;
    end

    TextStyleM.setTextStyle(effectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    local effectLabel = applyString(effectLabel, equipEffectTxt);

    -- 设置套装显示
    local suitNameLabel   = self.CT:getChildByName("suit_name");
    local suitSubLabel    = self.CT:getChildByName("suit_sub");
    local suitEffectLabel = self.CT:getChildByName("suit_effect");

    local suitId = equipInfo["suit"];
    if suitId and suitId ~= 0 then
        suitNameLabel:setVisible(true);
        suitSubLabel:setVisible(true);
        suitEffectLabel:setVisible(true);

        -- 套装信息
        local suitInfo = SuitM.query(suitId);
        if not suitInfo then
            error("获取不到套装(%d)信息", suitId);
            return;
        end

        local suits = suitInfo["active"];
        local suitCount = #suits;
        local suitActiveCount = 0;
        if suits then
            suitSubLabel:setVisible(true);
            local suitSub = "";
            for i = 1, suitCount do
                local equipId = suits[i];
                local itemName = ItemM.query(equipId, "name");
                local type = EquipM.query(equipId, "type")
                if EquipM.getEquip(type) == equipId then
                    -- 已经装备了，显示激活的颜色
                    suitActiveCount = suitActiveCount + 1;
                    itemName = "[brown]" .. itemName .. "[-]";
                elseif table.indexOf(table.keys(EquipM.queryEquipments(type)), equipId) > 0 then
                    -- 有，但是没装备，显示绿色
                    itemName = "[green]" .. itemName .. "[-]";
                else
                    -- 完全没这件，显示灰色
                    itemName = "[gray]" .. itemName .. "[-]";
                end

                suitSub = suitSub .. itemName;
                if i ~= suitCount then
                    suitSub = suitSub .. "\n";
                end
            end

            TextStyleM.setTextStyle(suitSubLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
            suitSubLabel = applyString(suitSubLabel, suitSub);
        end

        -- 设置套装名字
        local suitNameTxt = suitInfo["name"] .. "(" .. suitActiveCount .. "/" .. suitCount .. ")";
        TextStyleM.setTextStyle(suitNameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        suitNameLabel:setString(suitNameTxt);

        -- 设置套装效果 当套装效果未激活时，效果值显示为“？”；效果集齐时，显示具体属性
        local props = SuitM.calcSuitBaseProp(suitId);

        -- 工程学手册的额外加成效果
        props = table.append(props, EngineeringManualM.getManualAddition(suitId, "equip"));

        -- 合并下属性
        props = combineProps(props);

        local suitEffect = EquipM.getEquipPropDesc(props);

        if suitActiveCount == suitCount then
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
        else
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
        end
        suitEffectLabel = applyString(suitEffectLabel, suitEffect);
    else
        suitNameLabel:setVisible(false);
        suitSubLabel:setVisible(false);
        suitEffectLabel:setVisible(false);
    end

    local artifactTitleLabel = self.CT:getChildByName("artifact_upgrade");
    local artifacDescLabel = self.CT:getChildByName("artifact_upgrade_prop");

    if itemInfo.type == ITEM_TYPE_ARTIFACT then
        -- 设置神器强化属性
        artifactTitleLabel:setVisible(true);
        artifacDescLabel:setVisible(true);
        local level = ArtifactM.getArtifactLevel(self.classId);

        local starNode = self.CT:getChildByName("star_node");
        local rank = FormulaM.invoke("CALC_ARTIFACT_RANK", self.classId);
        local starLayer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");

        if starLayer then
            starNode:removeAllChildren();
            starNode:addChild(starLayer);
        end

        local artiMaxLevel = FormulaM.invoke("GET_ARTIFACT_MAX_LEVEL");

        TextStyleM.setTextStyle(artifactTitleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        artifactTitleLabel:setString(string.format(getLocStr("artifact_upgrade_title"), level, artiMaxLevel));

        local desc = ArtifactM.getUpgradePropDesc(self.classId, level);
        TextStyleM.setTextStyle(artifacDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
        artifacDescLabel = applyString(artifacDescLabel, desc);
    elseif HolyItemsM.isHolyItems(self.classId) then
        -- 如果是圣器，显示圣器的特殊属性
        artifactTitleLabel:setVisible(true);
        artifacDescLabel:setVisible(true);
        local level = HolyItemsM.getExtraLevel(self.classId);
        local maxLevel = HolyItemsM.query(self.classId, "max_extra_level");
        TextStyleM.setTextStyle(artifactTitleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);

        local itemType = HolyItemsM.query(self.classId, "type") or "";
        if itemType == "machine" then
            artifactTitleLabel:setString(string.format(getLocStr("machine_upgrade_title"), level, maxLevel));
        else
            artifactTitleLabel:setString(string.format(getLocStr("holy_items_upgrade_title"), level, maxLevel));
        end

        -- 获取圣器的特殊属性描述
        local desc = HolyItemsM.getExtraPropDesc(self.classId);
        if level > 0 then
            TextStyleM.setTextStyle(artifacDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
        else
            TextStyleM.setTextStyle(artifacDescLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY, nil, nil, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
        end
        artifacDescLabel = applyString(artifacDescLabel, desc);
    else
        artifactTitleLabel:setVisible(false);
        artifacDescLabel:setVisible(false);
    end

    -- 重绘按钮
    self:redrawButtons();

    -- 自适应所有组件
    local btnEquipSet = self.CT:getChildByName("btn_equip_mount");
    local btnEquipMerge = self.CT:getChildByName("btn_equip_merge");
    local btnEquipdismount = self.CT:getChildByName("btn_equip_dismout");

    local bg = findChildByName(self.node, "CT/bg");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, effectLabel, suitNameLabel, suitSubLabel,
          suitEffectLabel, artifactTitleLabel, artifacDescLabel, btnEquipSet,
          btnEquipMerge });

    btnEquipdismount:setPositionY(btnEquipMerge:getPositionY());

    -- 星星与装备名称在同一行
    starNode:setPositionY(nameLabel:getPositionY());
end

-- 重绘按钮
function UIEquipsOperation:redrawButtons()
    -- 设置装备/卸下
    local isEquip = self:isEquip(self.classId);
    local btnEquipSet = self.CT:getChildByName("btn_equip_mount");
    local btnEquipMerge = self.CT:getChildByName("btn_equip_merge");
    local btnEquipdismount = self.CT:getChildByName("btn_equip_dismout");

    btnEquipMerge:setVisible(false);
    btnEquipdismount:setVisible(false);

    -- 如果是装备
    local btnResolve = findChildByName(self.node, "BT/btn_resolve");
    if isEquip then
        if self.operateType == EQUIP_OPERATE_EQUIP then
            -- 装备
            btnEquipSet:setTitleText(getLocStr("btn_text_equip"));
        elseif self.operateType == EQUIP_OPERATE_BLACKSMITH or
            self.operateType == EQUIP_OPERATE_SUBMIT then
            -- 物品提交操作
            btnEquipSet:setTitleText(getLocStr("btn_text_select"));

            -- 将分解按钮设置不可点击
            btnResolve:setBright(false);
            btnResolve:setTouchEnabled(false);
        elseif self.operateType == EQUIP_OPERATE_RISKER then
            -- 检查装备功能属性
            local needShow = false;
            local props = PropM.fetchProps(ME.user, "upgrade_equip");

            for _, prop in ipairs(props) do
                -- 升级魔法套装
                if prop[2] == "magic" or prop[2] == "physic" then
                    -- 升级套装
                    btnEquipSet:setTitleText(getLocStr("btn_text_upgrade_suit"));
                    btnEquipSet:setVisible(true);
                    needShow = true;
                    break;
                elseif prop[2] == "forging" then
                    -- 锻造宝物
                    btnEquipSet:setTitleText(getLocStr("btn_text_forge_treasure"));
                    btnEquipSet:setVisible(true);
                    needShow = true;
                    break;
                end

            end

            -- 检查合成
            local propCompound = PropM.fetchProps(ME.user, "synthesis_reel");

            for _, prop in ipairs(propCompound) do
                -- 升级魔法套装
                if prop[2] == 1 then
                    -- 合成卷轴
                    btnEquipSet:setTitleText(getLocStr("btn_text_compound_spell_2"));
                    btnEquipSet:setVisible(true);
                    needShow = true;
                    break;
                end
            end

            if not needShow then
                btnEquipSet:setVisible(false);
            end

            -- 将分解按钮设置不可点击
            btnResolve:setBright(false);
            btnResolve:setTouchEnabled(false);
        else
            -- 能够融合的套装
            local suitId = SuitM.get_suit_id(self.classId);
            if suitId > 0 and type(SuitM.query(suitId, "merge_bonus")) == "number" and SuitM.canShowBtnMerge(suitId) then
                btnEquipSet:setVisible(false);

                -- 显示融合、卸下两个按钮
                btnEquipMerge:setVisible(true);
                btnEquipdismount:setVisible(true);

                btnEquipMerge:setBright(SuitM.canMergeEquip(self.classId));

                btnEquipMerge:setTitleText(getLocStr("btn_text_merge"));
                btnEquipdismount:setTitleText(getLocStr("btn_text_unload"));
            else
                -- 卸下
                btnEquipSet:setTitleText(getLocStr("btn_text_unload"));
            end

            -- 将分解按钮设置不可点击
            btnResolve:setBright(false);
            btnResolve:setTouchEnabled(false);
        end
    else
        -- 武器/徽章
        btnEquipSet:setTitleText(getLocStr("btn_text_unload"));
        btnEquipSet:setBright(false);
        btnEquipSet:setTouchEnabled(false);

        -- 将分解按钮设置不可点击
        local btnResolve = findChildByName(self.node, "BT/btn_resolve");
        btnResolve:setBright(false);
        btnResolve:setTouchEnabled(false);
    end

    local itemType = ItemM.query(self.classId, "type");
    local cantSplit = EquipM.query(self.classId,"dbase")["cant_split"];
    if itemType == ITEM_TYPE_ARTIFACT or cantSplit == 1 then
        -- 是神器，或者配置了无法分解，分解按钮需要置灰
        local btnResolve = findChildByName(self.node, "BT/btn_resolve");
        btnResolve:setBright(false);
        btnResolve:setTouchEnabled(false);
    end
end

-- 判断是否是装备 否则就是武器/徽章
function UIEquipsOperation:isEquip(classId)
    local type = EquipM.query(classId, "type");
    if type == EQUIP_TYPE_WEAPON or type == EQUIP_TYPE_MEDAL then
        return false;
    end
    return true;
end

-- 适配
function UIEquipsOperation:resize()
    local w = AlignM.frameSize.width;
    local h = AlignM.frameSize.height;

    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 用于计算直接装备带来的血量魔量绝对值提升
function UIEquipsOperation:getAttrib(classId, attrib)
    local props = table.deepcopy(EquipM.calcBaseProp(ME.user, classId));
    local value = 0;

    -- 获取工程学手册对装备的额外加成
    local manualAddition = EngineeringManualM.getManualAddition(classId, "equip");
    if manualAddition then
        props = table.append(props, manualAddition);
    end

    -- 如果是神器，加上神器升级带来的附加属性
    if ArtifactM.isArtifact(classId) then
        props = table.append(props, ArtifactM.getExtraProps(classId));
    end

    -- 如果是阿拉丁神灯，需要获取额外的属性
    if DesertAltarM.isAladdinLamp(classId) then
        props = table.append(props, DesertAltarM.getLampProp(classId));
    end

    for i = 1, #props do
        if props[i][1] == 200 and props[i][2] == attrib then
            value = props[i][3];
            break;
        end
    end
    return value;
end

-- 注册点击事件
function UIEquipsOperation:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
        end
    end
    AddTouchEventListener(btnBack, onBackClick);
    AddBackEventHandler(self, btnBack, btnBack.touchEventListener);

    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册装备按钮点击事件
    local btnEquipSet = self.CT:getChildByName("btn_equip_mount");
    local btnEquipMerge = self.CT:getChildByName("btn_equip_merge");
    local btnEquipdismount = self.CT:getChildByName("btn_equip_dismout");
    local function onEquipSetOnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended  then
            AudioM.playFx("equip_put");
            if self.operateType == EQUIP_OPERATE_EQUIP then
                -- 装备
                local type = EquipM.query(self.classId, "type");
                local equipClassId = EquipM.getEquip(type, 1);
                if not equipClassId then
                    DungeonActionM.go("do_equip", 0, self.classId);

                    -- 关闭当前界面
                    UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
                    return;
                end

                -- 获得新装备增加的血量
                local newHp = self:getAttrib(self.classId, "max_hp");
                local newMp = self:getAttrib(self.classId, "max_mp");

                local oldHp = self:getAttrib(equipClassId, "max_hp");
                local oldMp = self:getAttrib(equipClassId, "max_mp");

                -- 考虑套装加成
                local oldEquipList = {};
                local newEquipList = {};
                    -- 遍历每个部位
                    for _, equiped in pairs(ME.user.equipments) do
                    -- 遍历该部位的所有已穿戴装备
                    for _, e in pairs(equiped) do
                        if EquipM.isEquipment(e) then
                            table.insert(oldEquipList, e);
                            if e == equipClassId then
                                table.insert(newEquipList, self.classId);
                            else
                                table.insert(newEquipList, e);
                            end
                        end
                    end
                end

                local newSuitHp = 0;
                local newSuitMp = 0;
                local oldSuitHp = 0;
                local oldSuitMp = 0;

                if SuitM.isSuitByEquipId(oldEquipList, equipClassId) then
                    -- 旧装备情况下是套装
                    oldSuitHp = SuitM.getSuitPropByEquipId(equipClassId, "max_hp")[3] or 0;
                    oldSuitMp = SuitM.getSuitPropByEquipId(equipClassId, "max_mp")[3] or 0;
                end

                if SuitM.isSuitByEquipId(newEquipList, self.classId) then
                    -- 新装备情况下是套装
                    newSuitHp = SuitM.getSuitPropByEquipId(self.classId, "max_hp")[3] or 0;
                    newSuitMp = SuitM.getSuitPropByEquipId(self.classId, "max_mp")[3] or 0;
                end

                -- 称号百分比加成
                local skills = ME.user:getAllSkills();
                local maxHpUp = 0;
                local maxMpUp = 0;
                for _, skillId in pairs(skills) do
                    local skillId = FormulaM.invoke("CALC_FINAL_SKILL", ME.user, skillId);
                    local infos = SkillM.getSkillHpMpUp(skillId);
                    for _, info in pairs(infos) do
                        local para = info["para"];
                        if para[2] == "max_hp" then
                            maxHpUp = maxHpUp + para[3];
                        elseif para[2] == "max_mp" then
                            maxMpUp = maxMpUp + para[3];
                        end
                    end
                end
                local extraHp = (newHp + newSuitHp - oldHp - oldSuitHp) * maxHpUp / 1000;
                local extraMp = (newMp + newSuitMp - oldMp - oldSuitMp) * maxMpUp / 1000;

                if ME.user:getHp() - oldHp - oldSuitHp + newHp + newSuitHp + extraHp <= 0 then
                    -- 提示血量不足 不能更换装备
                    alert(getLocStr("change_equip_hp_not_enough"));

                    -- 关闭当前界面
                    UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
                    return;
                elseif ME.user:getMp() - oldMp - oldSuitMp + newMp + newSuitMp + extraMp < 0 then
                    -- 魔法值不足 不能更换装备
                    alert(getLocStr("change_equip_mp_not_enough"));

                    -- 关闭当前界面
                    UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
                    return;
                end

                -- 强制替换
                local pos = 1;  --- forceEquip * 2 + forceChange;
                DungeonActionM.go("do_equip", pos, self.classId)
            elseif self.operateType == EQUIP_OPERATE_BLACKSMITH then
                -- 选择
                -- 抛出选择装备的事件
                EventMgr.fire(event.BLACKSMITH_INPUT_EQUIP,
                    table.add({ ["classId"] = self.classId, ["isEquiped"] = self.isEquiped}, self.extraPara));

                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");

                -- 关闭装备界面
                closeEquipUI();
            elseif self.operateType == EQUIP_OPERATE_SUBMIT then

                -- 如果是穿着的装备，那么需要先脱下来
                if self.isEquiped then
                    -- 判断能否卸下
                    local ifCanUnload = self:canUnequip();
                    if ifCanUnload then
                        -- 先卸下装备
                        local type = EquipM.query(self.classId,"type");
                        AudioM.playFx("equip_unload");
                        DungeonActionM.go("do_unequip", 1, type);
                    else
                        -- 关闭当前界面
                        UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
                        return;
                    end
                end

                -- 抛出选择装备的事件 (这里有个隐含的假设， 用到这个消息的各个窗口是互斥的，否则会有问题)
                EventMgr.fire(event.BLACKSMITH_INPUT_EQUIP,
                    table.add({ ["classId"] = self.classId, ["isEquiped"] = self.isEquiped}, self.extraPara));

                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");

                -- 关闭装备界面
                closeEquipUI();
            elseif self.operateType == EQUIP_OPERATE_RISKER then
                -- 检查装备功能属性
                local needShow = false;
                local props = PropM.fetchProps(ME.user, "upgrade_equip");
                for _, prop in ipairs(props) do
                    -- 升级魔法套装
                    if prop[2] == "magic" then
                        require "game/ui/form/risker_equip/UIMagicAnvil";
                        -- 关闭当前界面
                        UIMgr.getCurrentScene():removeFormByName("UIMagicAnvil");
                        local uiForm = UIMagicAnvil.create(self.classId, EQUIP_STYLE_MAGIC);
                        UIMgr.getCurrentScene():addForm(uiForm);
                        break;
                    elseif prop[2] == "physic" then
                        require "game/ui/form/risker_equip/UIMagicAnvil";
                        -- 关闭当前界面
                        UIMgr.getCurrentScene():removeFormByName("UIMagicAnvil");
                        local uiForm = UIMagicAnvil.create(self.classId, EQUIP_STYLE_PHYSIC);
                        UIMgr.getCurrentScene():addForm(uiForm);
                        break;
                    elseif prop[2] == "forging" then
                        -- 锻造宝物
                        require "game/ui/form/risker_equip/UIChooseEquip";
                        -- 关闭当前界面
                        UIMgr.getCurrentScene():removeFormByName("UIChooseEquip");
                        local uiForm = UIChooseEquip.create(self.classId);
                        UIMgr.getCurrentScene():addForm(uiForm);
                        break;
                    end

                end

                -- 检查合成
                local propCompound = PropM.fetchProps(ME.user, "synthesis_reel");
                for _, prop in ipairs(propCompound) do
                    -- 升级魔法套装
                    if prop[2] == 1 then
                        -- 合成卷轴
                        require "game/ui/form/risker_equip/UIChooseSpell";
                        -- 关闭当前界面
                        UIMgr.getCurrentScene():removeFormByName("UIChooseSpell");
                        local uiForm = UIChooseSpell.create(self.classId);
                        UIMgr.getCurrentScene():addForm(uiForm);
                        break;
                    end
                end

            else
                -- 卸下
                -- 判断能否卸下
                local ifCanUnload = self:canUnequip();
                if ifCanUnload then
                    local type = EquipM.query(self.classId,"type");
                    AudioM.playFx("equip_unload");
                    DungeonActionM.go("do_unequip", 1, type);
                end
            end

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
        end
    end

    local function onMergeSuitOnClick(sender, eventType)
        -- 如果是可融合的套装
        local suitId = SuitM.get_suit_id(self.classId);
        if suitId > 0 and type(SuitM.query(suitId, "merge_bonus")) == "number" then
            -- 如果可以融合
            if SuitM.canMergeSuit(suitId) then

                local function okFunc()
                    DungeonActionM.go("merge_suit", suitId);
                end

                local suitName = SuitM.query(suitId, "name");
                local mergeName = ItemM.query(SuitM.query(suitId, "merge_bonus"), "name");

                confirm2(
                    CONFIRM_TYPE_OK_CANCEL,
                    getLocStr("element_suit_merge_title"),
                    string.format(getLocStr("element_suit_merge_msg"), suitName, mergeName),
                    okFunc
                );

                -- 关闭当前界面
                UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
            end

            return;
        end
    end

    btnEquipSet:addTouchEventListener(onEquipSetOnClick);
    TextStyleM.setTextStyle(btnEquipSet, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    btnEquipMerge:addTouchEventListener(onMergeSuitOnClick);
    TextStyleM.setTextStyle(btnEquipMerge, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    btnEquipdismount:addTouchEventListener(onEquipSetOnClick);
    TextStyleM.setTextStyle(btnEquipdismount, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);

    -- 注册分解按钮点击事件
    local btnResolve = findChildByName(node, "BT/btn_resolve");
    local function onResolveOnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            self:showResolveConfirm(self.classId);
        end
    end
    btnResolve:addTouchEventListener(onResolveOnClick);
    TextStyleM.setTextStyle(btnResolve, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnResolve:setTitleText(getLocStr("btn_text_resolve"));
end

function UIEquipsOperation:showResolveConfirm(classId)
    -- 获取拥有的数量
    local ownAmount = ItemM.getAmount(ME.user, classId);

    -- 分解全部
    local splitAll = function()
        DungeonActionM.go("split_equip", classId, ownAmount)

        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
    end

    -- 分解一个
    local splitOne = function()
        -- 分解装备
        DungeonActionM.go("split_equip", classId, 1);
        UIMgr.getCurrentScene():removeFormByName("UIEquipsOperation");
    end

    local title = getLocStr("equip_split_title");

    local itemName = ItemM.query(classId, "name");
    local gainSp = FormulaM.invoke("CALC_SPLIT_EQUIP_GAIN_SP", classId);

    if ownAmount == 1 then
        -- 只有一个
        local msg = string.format(getLocStr("split_equip_confirm"), itemName, gainSp);
        local uiConfirm = confirm2(CONFIRM_TYPE_OK, title, msg, splitOne);
    else
        -- 有多个
        local msg = string.format(getLocStr("split_equip_confirm2"), itemName, gainSp,
            gainSp*ownAmount);
        local splitAllText = string.format(getLocStr("btn_text_split"), ownAmount);
        local splitOneText = string.format(getLocStr("btn_text_split"), 1);

        if getLang() ~= "zh" and getLang() ~= "tw" then
            splitAllText = getLocStr("btn_text_all");
            splitOneText = getLocStr("btn_text_one");
        end

        local uiConfirm = confirm2(CONFIRM_TYPE_OK_CANCEL, title, msg,
            splitAll,
            splitOne,
            splitAllText,
            splitOneText);
    end
end

-- 判断该装备是否可以卸下
function UIEquipsOperation:canUnequip()
    -- 判断卸下后英雄的血量及魔法值是否大于0
    local props = EquipM.calcBaseProp(ME.user, self.classId);
    local ifCanUnload = true;
    for i = 1, #props do

        if not ifCanUnload then
            return ifCanUnload;
        end

        local rule = PropM.query(props[i][1], "rule");

        if props[i][2] == "max_hp" then
            local value = PropM.getShieldHit();
            local curHp = ME.user:getHp();

            if value > 0 then
                curHp = curHp - value;
            end

            if props[i][3] >= curHp then
                ifCanUnload = false;
                alert(getLocStr("equip_hp_not_enough"));
            end
        elseif props[i][2] == "max_mp" then
            if props[i][3] > ME.user:getMp() then
                ifCanUnload = false;
                alert(getLocStr("equip_mp_not_enough"));
            end
        elseif (rule == "aid_attrib" or rule == "aid_attrib2") and (props[i][2] == "hp" or props[i][2] == "max_hp") then
            local arr = SummonM.findSummonsByActive();
            for _, grid in pairs(arr) do
                local summon = grid.summon;
                if SummonM.query(summon:query("classId"), "dbase")["equipment_add"] == 1
                    and summon:getHp() <= props[i][3] then
                    ifCanUnload = false;
                    alert(string.format(getLocStr("summon_low_hp"), summon:query("name")));
                    break;
                end
            end
        end
    end

    return ifCanUnload;
end
